import { Init, Provide,Inject } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { FollowUserInfoEntity } from '../entity/info';

/**
 * follow模块-用户关注信息
 */
@Provide()
export class FollowUserInfoService extends BaseService {
  @InjectEntityModel(FollowUserInfoEntity)
  followUserInfoEntity: Repository<FollowUserInfoEntity>;

  @Inject()
  ctx;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.followUserInfoEntity);
  }

  
  // 用户关注 
  async updateFollow(queryData: any) {
    console.log(queryData, 'queryData')
    let userId = this.ctx.header.token
    if(!userId){
      throw new Error('请登陆后操作');
    }
    let data = await this.followUserInfoEntity.findOneBy({
      userId,
      followId: queryData.id,
    })
    if (data) {
      let res = await this.followUserInfoEntity.update({
        userId,
        followId: queryData.id,
      }, {
        followStatus: queryData.isFollow ? 1 : 0,
      })
      return res
    } else {
      let params = {
        userId,
        followId: queryData.id,
        followStatus: queryData.isFollow ? 1 : 0,
        remark: "",
        followTime: new Date(),
      }
      let res = await this.followUserInfoEntity.save(params)
      return res
    }
  }

  // 获取我的关注
  async getFollow(queryData: any) {
    let userId = this.ctx.header.token
    let sql = "select * from follow_user_info where followStatus = 1 and userId = " + userId + " ORDER BY createTime DESC"
    let res = await this.sqlRenderPage(sql, queryData, false);
    if (res.list.length) {
      let resSql = res.list.map(o => o.followId).join(',')
      let photoSql = "select * from demo_user_info where id IN ( " + resSql + " ) ORDER BY createTime DESC"
      let data: any = await this.nativeQuery(photoSql);
      data.forEach(element => {
        element.isFollow = true
      });
      res.list = data
    }
    return res
  }

}
